package com.huxiu.yd.fragments;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.DiscoveryDetailActivity;
import com.huxiu.yd.R;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by kHRYSTAL on 15/9/26:下午10:32.
 */
public class MyAttentionMassiveTestFragment extends Fragment implements
        OnRefreshListener2<ListView> {

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_attention_massive_test, container, false);
        ButterKnife.inject(this, view);
        adapter = new MyMassiveTestAdapter();
        View emptyView = view.findViewById(R.id.empty);
        list.setEmptyView(emptyView);
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setState(State.INIT_REFRESHING, true);
        return view;
    }

    private int currentPage = 0;

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(currentPage + 1);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        NetworkHelper.getInstance().getRequestQueue().cancelAll(this);
    }

    private List<DiscoveryItem> items = new ArrayList<>();

    MyMassiveTestAdapter adapter;

    private void getItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("act", "my_favorite");
        params.put("opt", "topic_activity");
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Method.POST,
                DiscoveryListResponse.class, true, params,
                new Listener<DiscoveryListResponse>() {
                    @Override
                    public void onResponse(DiscoveryListResponse response) {
                        if (response.isSuccess()) {
                            if (page == 0) {
                                items.clear();
                            }
                            Collections.addAll(items, response.data);
                            adapter.notifyDataSetChanged();
                            currentPage = response.page;
                        } else {
                            Utils.showToast(response.msg);
                        }
                        refreshComplete();
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Utils.showErrorMsg(volleyError);
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private void refreshComplete() {
        if (list != null)
            list.postDelayed(new Runnable() {
                @Override
                public void run() {
                    list.onRefreshComplete();
                }
            }, 100);
    }

    private class MyMassiveTestAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public DiscoveryItem getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            final ViewHolder vh;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.my_attention_massive_test_list_item, parent, false);
                vh = new ViewHolder(view);
                view.setTag(vh);
            } else {
                vh = (ViewHolder) view.getTag();
            }
            final DiscoveryItem item = getItem(position);
            ImageLoader.getInstance()
                    .displayImage(item.image, vh.image, ImageUtils.getProductDisplayOption(item
                            .getProductPlaceHolder()));
            vh.title.setText(item.title);
            vh.like.setImageResource(
                    item.liked() ? R.drawable.favorite_yes : R.drawable.favorite_no);
            vh.likeLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    like(item, vh);
                }
            });
            vh.image.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), DiscoveryDetailActivity.class);
                    intent.putExtra(Constants.MASSIVE_TEST_ITEM_KEY, item.toString());
                    startActivity(intent);
                }
            });
            vh.title.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), DiscoveryDetailActivity.class);
                    intent.putExtra(Constants.MASSIVE_TEST_ITEM_KEY, item.toString());
                    startActivity(intent);
                }
            });
            vh.enrolledUserCount.setText("报名人数：" + item.member_num);
            return view;
        }


    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file
     * 'my_attention_massive_test_list_item.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers
     *         (http://github.com/avast)
     */
    static class ViewHolder {
        @InjectView(R.id.enrolled_user_count)
        TextView enrolledUserCount;

        @InjectView(R.id.image)
        ImageView image;

        @InjectView(R.id.like)
        ImageView like;

        @InjectView(R.id.like_layout)
        FrameLayout likeLayout;

        @InjectView(R.id.divider)
        View divider;

        @InjectView(R.id.title)
        TextView title;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private void like(final DiscoveryItem item, final ViewHolder vh) {
        String url = NetworkConstants.TOPIC_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "user_operate");
        params.put("id", String.valueOf(item.id));
        params.put("operate_type", "favorite");
        params.put("type", item.liked() ? "2" : "1");
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Method.POST, BaseResponse.class,
                true, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    if (item.like_status == 1) {
                        item.like_status = 0;
                        Utils.showToast("取消成功");
                    } else {
                        item.like_status = 1;
                        Utils.showToast("关注成功");
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showErrorMsg(error);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }
}
